package com.oa.rc.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.rc.entity.RcSchedule;
import com.oa.rc.entity.RcScheduleExec;
import com.oa.rc.entity.RcScheduleRecord;
import com.oa.rc.service.RcScheduleExecService;
import com.oa.rc.service.RcScheduleRecordService;
import com.oa.rc.service.RcScheduleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/**/oa/rc/rcSchedule")
@Api(tags = {"rc_schedule-操作接口"})
public class RcScheduleController {

    static Logger logger = LoggerFactory.getLogger(RcScheduleController.class);

    @Autowired
    private RcScheduleService rcScheduleService;
    @Autowired
    private RcScheduleRecordService rcScheduleRecordService;
    @Autowired
    private RcScheduleExecService rcScheduleExecService;

    @ApiOperation(value = "rc_schedule-查询列表", notes = " ")
    @ApiEntityParams(RcSchedule.class)
    @ApiResponses({@ApiResponse(code = 200, response = RcSchedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listRcSchedule(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        QueryWrapper<RcSchedule> qw = QueryTools.initQueryWrapper(RcSchedule.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = rcScheduleService.selectListMapByWhere(page, qw, params);

        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "rc_schedule-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = RcSchedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addRcSchedule(@RequestBody RcSchedule rcSchedule) {
        String[] circcleDates = new String[0];
        Tips tips = new Tips("成功新增多条日程数据");
        try {
            try {
                if (StringUtils.isEmpty(rcSchedule.getId())) {
                    rcSchedule.setId(rcScheduleService.createKey("id"));
                } else {
                    RcSchedule rcScheduleQuery = new RcSchedule(rcSchedule.getId());
                    if (rcScheduleService.countByWhere(rcScheduleQuery) > 0) {
                        return Result.error("编号重复，请修改编号再提交");
                    }
                }
                Date nextUpdateTime;
                if ("date".equals(rcSchedule.getCircleType())) {
                    circcleDates = rcSchedule.getCirccleDates().split(",");
                } else {
                    circcleDates = rcScheduleExecService.setCirccleDates(rcSchedule);
                }
                rcSchedule.setExecCalcDate(new Date());
                rcSchedule.setCreateTime(new Date());
                rcSchedule.setStatus("0");
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    for (int x = 0; x < circcleDates.length - 1; x++) {
                        for (int y = x + 1; y < circcleDates.length; y++) {
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Date date1 = simpleDateFormat.parse(circcleDates[x]);
                            long ts1 = date1.getTime();
                            Date date2 = simpleDateFormat.parse(circcleDates[y]);
                            long ts2 = date2.getTime();
                            if (ts1 > ts2) {// 对时间进行排序
                                String temp = circcleDates[x];
                                circcleDates[x] = circcleDates[y];
                                circcleDates[y] = temp;
                            }
                        }
                    }
                    if ("week".equals(rcSchedule.getCircleType())) {
                        Date date = simpleDateFormat.parse(circcleDates[0]);
                        long ts = date.getTime() + 1000 * 60 * 60 * 24 * 7;
                        nextUpdateTime = new Date(ts);
                    } else if ("month".equals(rcSchedule.getCircleType())) {
                        Date parse = simpleDateFormat.parse(circcleDates[0]);
                        Calendar c = Calendar.getInstance();
                        c.setTime(parse);
                        /*int circcleDate = Integer.parseInt(circcleDates[0]);
                        c.set(Calendar.DAY_OF_MONTH,circcleDate);
                        nextUpdateTime=c.getTime();*/
                        int monday = c.get(Calendar.MONDAY) + 2;
                        if (c.get(Calendar.DATE) <= 28) {
                            if (monday < 12) {
                                if (monday < 10) {
                                    String setmonday = null;
                                    setmonday = "0" + monday;
                                }
                                nextUpdateTime = simpleDateFormat.parse((c.get(Calendar.YEAR) + "-" + monday + "-" + c.get(Calendar.DATE)));
                            } else {
                                nextUpdateTime = simpleDateFormat.parse(((c.get(Calendar.YEAR) + 1) + "-" + "1" + "-" + c.get(Calendar.DATE)));
                            }
                        } else {
                            Date date = simpleDateFormat.parse(circcleDates[0]);
                            long ts = date.getTime() + 1000 * 60 * 60 * 24 * 28;
                            nextUpdateTime = new Date(ts);
                        }
                    } else {
                        nextUpdateTime = null;
                    }
                    rcSchedule.setNextUpdateTime(nextUpdateTime);
                    List<RcScheduleExec> execs = new ArrayList<>();
                    List<RcScheduleRecord> Record = new ArrayList<>();
                    if ("1".equals(rcSchedule.getCircleable())) {
                        for (String circcleDate : circcleDates) {
                            RcScheduleExec rcScheduleExec = rcScheduleExecService.setRcScheduleExec(rcSchedule, circcleDate);
                            execs.add(rcScheduleExec);
                        }
                    }
                    if ("0".equals(rcSchedule.getCircleable())) {
                        Date date = new Date();
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                        Calendar c = Calendar.getInstance();
                        c.setTime(date);

                        int mm = c.get(Calendar.MONDAY) + 1;
                        String circcleDate = "";
                        if (mm > 12) {
                            circcleDate = c.get(Calendar.YEAR) + 1 + "-" + "01" + "-" + c.get(Calendar.DATE);
                        } else {
                            if (mm >= 10) {
                                circcleDate = c.get(Calendar.YEAR) + "-" + mm + "-" + c.get(Calendar.DATE);
                            } else {
                                circcleDate = c.get(Calendar.YEAR) + "-" + "0" + mm + "-" + c.get(Calendar.DATE);
                            }
                        }
                        RcScheduleExec rcScheduleExec = rcScheduleExecService.setRcScheduleExec(rcSchedule, circcleDate);
                        execs.add(rcScheduleExec);
                    }
                    rcScheduleService.insert(rcSchedule);
                    rcScheduleExecService.batchInsert(execs);
                } catch (Exception e) {
                    tips.setErrMsg(e.getMessage());
                    logger.error("", e);
                }
            } catch (BizException e) {
                tips = e.getTips();
                logger.error("", e);
            } catch (Exception e) {
                tips.setErrMsg(e.getMessage());
                logger.error("", e);
            }
        } catch (BizException e) {
            tips = e.getTips();
            logger.error("", e);
        } catch (Exception e) {
            tips.setErrMsg(e.getMessage());
            logger.error("", e);
        }
        return Result.ok("add-ok", "添加成功！").setData(rcSchedule).setTips(LangTips.fromTips(tips));
    }

    @ApiOperation(value = "rc_schedule-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delRcSchedule(@RequestBody RcSchedule rcSchedule) {
        Tips tips = new Tips("成功删除一条数据");
        User user = LoginUtils.getCurrentUserInfo();
        if (!user.getUserid().equals(rcSchedule.getCreateUserid())) {
            return Result.error("只有创建人可以删除日程aaaa");
        }

        rcSchedule.setStatus("2");
        RcScheduleExec rcScheduleExec = new RcScheduleExec();
        rcScheduleExec.setScheduleId(rcSchedule.getId());
        rcScheduleExecService.toUpdateDeleteByWhere(rcScheduleExec);
        rcScheduleService.updateSomeFieldByPk(rcSchedule);

        return Result.ok("del-ok", "删除成功！").setTips(LangTips.fromTips(tips));
    }

    @ApiOperation(value = "rc_schedule-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = RcSchedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editRcSchedule(@RequestBody RcSchedule rcSchedule) {
        Tips tips = new Tips("成功更新一条数据");
        User user = LoginUtils.getCurrentUserInfo();

        try {
            String[] circcleDates;
            RcSchedule oldrcSchedule = rcScheduleService.selectOneObject(rcSchedule);
            if (!oldrcSchedule.getCreateUserid().equals(rcSchedule.getCreateUserid())) {
                return Result.error("只有创建人可以修改日程");
            }
            rcSchedule.setExecCalcDate(new Date());
            rcSchedule.setStatus(oldrcSchedule.getStatus());
         /*   if(!StringUtils.hasText(rcSchedule.getCircleType())
                    ||"1".equals(oldrcSchedule.getCircleable())
                    ||"0".equals(rcSchedule.getCircleable())
                    ||!oldrcSchedule.getCircleType().equals(rcSchedule.getCircleType())
                    ||!oldrcSchedule.getCircleDaysOfWeek().equals(rcSchedule.getCircleDaysOfWeek())
                    ||!oldrcSchedule.getCircleDaysOfMonth().equals(rcSchedule.getCircleDaysOfMonth())
                    ||!oldrcSchedule.getCirccleDates().equals(rcSchedule.getCirccleDates())
            ){*/
            RcScheduleExec rcScheduleExecDb = new RcScheduleExec();
            rcScheduleExecDb.setScheduleId(rcSchedule.getId());
            if ("1".equals(oldrcSchedule.getCircleable())) {
                rcScheduleExecService.toUpdateDeleteByWhere(rcScheduleExecDb);
            }
            if ("1".equals(rcSchedule.getCircleable())) {
                Date nextUpdateTime;
                if ("date".equals(rcSchedule.getCircleType())) {
                    circcleDates = rcSchedule.getCirccleDates().split(",");
                } else {
                    circcleDates = rcScheduleExecService.setCirccleDates(rcSchedule);
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                for (int x = 0; x < circcleDates.length - 1; x++) {
                    for (int y = x + 1; y < circcleDates.length; y++) {
                        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date date1 = simpleDateFormat.parse(circcleDates[x]);
                        long ts1 = date1.getTime();
                        Date date2 = simpleDateFormat.parse(circcleDates[y]);
                        long ts2 = date2.getTime();
                        if (ts1 > ts2) {// 对时间进行排序
                            String temp = circcleDates[x];
                            circcleDates[x] = circcleDates[y];
                            circcleDates[y] = temp;
                        }
                    }
                }
                if ("week".equals(rcSchedule.getCircleType())) {
                    Date date = simpleDateFormat.parse(circcleDates[0]);
                    long ts = date.getTime() + 1000 * 60 * 60 * 24 * 7;
                    nextUpdateTime = new Date(ts);
                } else if ("month".equals(rcSchedule.getCircleType())) {
                    Date parse = simpleDateFormat.parse(circcleDates[0]);
                    Calendar c = Calendar.getInstance();
                    /*int circcleDate = Integer.parseInt(circcleDates[0]);
                    c.set(Calendar.DAY_OF_WEEK,circcleDate);
                    nextUpdateTime = c.getTime();*/
                    int monday = c.get(Calendar.MONDAY) + 2;
                    if (c.get(Calendar.DATE) <= 28) {
                        if (monday < 12) {
                            nextUpdateTime = simpleDateFormat.parse((c.get(Calendar.YEAR) + "-" + monday + "-" + c.get(Calendar.DATE)));
                        } else {
                            nextUpdateTime = simpleDateFormat.parse(((c.get(Calendar.YEAR) + 1) + "-" + 1 + "-" + c.get(Calendar.DATE)));
                        }
                    } else {
                        Date date = simpleDateFormat.parse(circcleDates[0]);
                        long ts = date.getTime() + 1000 * 60 * 60 * 24 * 28;
                        nextUpdateTime = new Date(ts);
                    }
                } else {
                    nextUpdateTime = null;
                }
                rcSchedule.setNextUpdateTime(nextUpdateTime);
                List<RcScheduleExec> execs = new ArrayList<>();
                List<RcScheduleRecord> Record = new ArrayList<>();
                for (String circcleDate : circcleDates) {
                    RcScheduleExec rcScheduleExec = rcScheduleExecService.setRcScheduleExec(rcSchedule, circcleDate);
                    execs.add(rcScheduleExec);
                }
                rcScheduleExecService.batchInsert(execs);
            }
            if ("0".equals(rcSchedule.getCircleable())) {
//                rcScheduleExecService.
            }
//            }
            rcScheduleService.rcScheduleUpdateSomeFieldByPk(rcSchedule);
//            rcScheduleService.updateSomeFieldByPk(rcSchedule);
        } catch (BizException e) {
            tips = e.getTips();
            logger.error("", e);
        } catch (Exception e) {
            tips.setErrMsg(e.getMessage());
            logger.error("", e);
        }
        return Result.ok("edit-ok", "修改成功！").setData(rcSchedule);
    }


    @ApiOperation(value = "根据主键列表批量修改rc_schedule信息", notes = "batchEditRcSchedule,仅需要上传主键字段")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchComplete", method = RequestMethod.POST)
    public Result batchEditRcSchedule(@RequestBody List<RcSchedule> rcSchedules) {
//        Tips tips = new Tips("成功修改" + rcSchedules.size() + "条数据");
        rcScheduleService.batchUpdate(rcSchedules);
        return Result.ok();
    }

    @RequestMapping(value = "/listRcScheduleByDay", method = RequestMethod.GET)
    public Result listRcScheduleByDay(@RequestParam Map<String, Object> params) {
        Map<String, Object> m = new HashMap<>();
        RequestUtils.transformArray(params, "ids");

        QueryWrapper<RcSchedule> qw = QueryTools.initQueryWrapper(RcSchedule.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> rcScheduleList = rcScheduleService.selectListRcScheduleByDate(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(rcScheduleList);
    }


    //按照月份查询当前用户的日程
    @RequestMapping(value = "/listRcScheduleByMonth", method = RequestMethod.GET)
    public Result listRcScheduleByMonth(@RequestParam Map<String, Object> params) {
        Map<String, Object> params1 = new HashMap<>();
        params1.put("execDateMonth", (params.get("month")));
        params1.put("createUserid", params.get("receiveUserid"));
        if (!StringUtils.isEmpty(params.get("pageNum")) && !StringUtils.isEmpty(params.get("pageSize"))) {
            params1.put("pageNum", params.get("pageNum"));
            params1.put("pageSize", params.get("pageSize"));
        }
        params1.put("orderBy", "exec_calc_date desc");
        RequestUtils.transformArray(params1, "ids");

        List<Map<String, Object>> rcScheduleList = rcScheduleService.selectListScheduleMapByWhere(params1);

        return Result.ok("query-ok", "查询成功").setData(rcScheduleList);
    }

    @ApiOperation(value = "rc_schedule-批量修改某些字段", notes = "")
    @ApiEntityParams(value = RcSchedule.class, props = {}, remark = "rc_schedule", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = RcSchedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        rcScheduleService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "rc_schedule-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelRcSchedule(@RequestBody List<RcSchedule> rcSchedules) {
        User user = LoginUtils.getCurrentUserInfo();
        if (rcSchedules.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<RcSchedule> datasDb = rcScheduleService.listByIds(rcSchedules.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<RcSchedule> can = new ArrayList<>();
        List<RcSchedule> no = new ArrayList<>();
        for (RcSchedule data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            rcScheduleService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "rc_schedule-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = RcSchedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(RcSchedule rcSchedule) {
        RcSchedule data = (RcSchedule) rcScheduleService.getById(rcSchedule);
        return Result.ok().setData(data);
    }

}
